| Total Complexity | 7 |
| Total Lines | 38 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 0 | ||
| 1 | import {IObserver} from '@enbock/state-value-observer/Observer'; |
||
| 8 | |||
| 9 | 1 | export default class Router { |
|
| 10 | currentPage: IObserver<IPageData | null>; |
||
| 11 | history: History; |
||
| 12 | |||
| 13 | constructor(pageObserver: IObserver<IPageData | null>, history: History) { |
||
| 14 | 5 | this.currentPage = pageObserver; |
|
| 15 | 5 | this.history = history; |
|
| 16 | } |
||
| 17 | |||
| 18 | 1 | attachTo(window: Window) { |
|
| 19 | 2 | window.addEventListener('popstate', this.onHistoryChange.bind(this)); |
|
| 20 | } |
||
| 21 | |||
| 22 | 1 | initialize(): void { |
|
| 23 | 2 | if (this.currentPage.value == null) return; |
|
| 24 | 1 | const firstPage: IPageData = this.currentPage.value; |
|
| 25 | 1 | this.history.replaceState(firstPage, firstPage.name, firstPage.baseUrl); |
|
| 26 | 1 | this.updatePage(firstPage); |
|
| 27 | } |
||
| 28 | |||
| 29 | 1 | changePage(newPage: IPageData): void { |
|
| 30 | 2 | const currentPage: IPageData | null = this.currentPage.value; |
|
| 31 | 4 | if (currentPage != null && currentPage.name == newPage.name) { |
|
| 32 | 1 | return; |
|
| 33 | } |
||
| 34 | |||
| 35 | 1 | this.history.replaceState(newPage, newPage.name, newPage.currentUrl); |
|
| 36 | 1 | this.updatePage(newPage); |
|
| 37 | } |
||
| 38 | |||
| 39 | 1 | protected updatePage(page: IPageData): void { |
|
| 40 | 3 | this.currentPage.value = page; |
|
| 41 | } |
||
| 42 | |||
| 43 | 1 | protected onHistoryChange(event: PopStateEvent): void { |
|
| 44 | 1 | const newPage: IPageData = event.state as IPageData; |
|
| 45 | 1 | this.updatePage(newPage); |
|
| 46 | } |
||
| 48 |